package com.m20studio.mop.activity;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager.LayoutParams;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.m20studio.mop.R;
import com.m20studio.mop.db.DBHelper;
import com.m20studio.mop.http.HttpConnectionUtil;
import com.m20studio.mop.http.HttpConnectionUtil.HttpConnectionCallback;
import com.m20studio.mop.http.HttpConnectionUtil.HttpMethod;
import com.m20studio.mop.menu.GridHandler;
import com.m20studio.mop.menu.GridInfo;
import com.m20studio.mop.util.ClassArray;
import com.m20studio.mop.xml.XMLFeed;
import com.m20studio.mop.xml.XMLHandler;

public class ClassTZ extends Activity implements OnItemClickListener{
	
	private ListView classContent;
	private int lmId;
	private int classId;
	private String url;
	private LinearLayout classButtonDzh,classButtonDxj,classButtonQch,classButtonYcq,classButtonRrss;
	private List<XMLFeed> xmllists;
	private List<GridInfo> gridlists;
	private SimpleAdapter adapter;
	private LinearLayout topBarMore;
	private LinearLayout topBarPrevious;
	private LinearLayout topBarNext;
	private int page = 1;
	private LinearLayout loading;
	private AnimationDrawable loadingAnim;
	private TextView pageInfo;
	private DBHelper dbHelper;
	private LinearLayout classMoreB1,classMoreB2,classMoreB3,classMoreB4,classMoreB5;
	private int moreNum = 1;
	private TextView topTitle;
  	private boolean menuDisplay = false;	
  	private GridView classtzMenu; 
    private SimpleAdapter gridAdapter;
    private RelativeLayout classtz_menu_re;
    private boolean moreDisplay;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.classtz);
        /////////////////////onCreate开始///////////////////////// 
        
        //获取传参
      	Bundle extras = getIntent().getExtras();
        lmId = extras.getInt("lmId");
        classId = extras.getInt("classId");
        
        //设置底部按钮
        classButtonDzh = (LinearLayout) findViewById(R.id.classtz_bottom_bar_button_dzh);
        classButtonDxj = (LinearLayout) findViewById(R.id.classtz_bottom_bar_button_dxj);
        classButtonQch = (LinearLayout) findViewById(R.id.classtz_bottom_bar_button_qch);
        classButtonYcq = (LinearLayout) findViewById(R.id.classtz_bottom_bar_button_ycq);
        classButtonRrss = (LinearLayout) findViewById(R.id.classtz_bottom_bar_button_rrss);
        
        classButtonDzh.setOnClickListener(new View.OnClickListener() { 
        	public void onClick(View v){
	            Intent intent = new Intent();
	    	  	intent.putExtra("lmId", 0);
	    	  	intent.putExtra("classId", 0);
	    	  	intent.setAction("com.m20studio.mop.activity.ClassTZ");
	    	  	startActivity(intent);
	        } 
		});
        classButtonDxj.setOnClickListener(new View.OnClickListener() { 
        	public void onClick(View v){
	            Intent intent = new Intent();
	    	  	intent.putExtra("lmId", 1);
	    	  	intent.putExtra("classId", 0);
	    	  	intent.setAction("com.m20studio.mop.activity.ClassTZ");
	    	  	startActivity(intent);
	        } 
		});
        classButtonQch.setOnClickListener(new View.OnClickListener() { 
        	public void onClick(View v){
	            Intent intent = new Intent();
	    	  	intent.putExtra("lmId", 2);
	    	  	intent.putExtra("classId", 0);
	    	  	intent.setAction("com.m20studio.mop.activity.ClassTZ");
	    	  	startActivity(intent);
	        } 
		});
        classButtonYcq.setOnClickListener(new View.OnClickListener() { 
        	public void onClick(View v){
	            Intent intent = new Intent();
	    	  	intent.putExtra("lmId", 3);
	    	  	intent.putExtra("classId", 0);
	    	  	intent.setAction("com.m20studio.mop.activity.ClassTZ");
	    	  	startActivity(intent);
	        } 
		});
        classButtonRrss.setOnClickListener(new View.OnClickListener() { 
        	public void onClick(View v){
	            Intent intent = new Intent();
	    	  	intent.putExtra("lmId", 4);
	    	  	intent.putExtra("classId", 0);
	    	  	intent.setAction("com.m20studio.mop.activity.ClassTZ");
	    	  	startActivity(intent);
	        } 
		});
        
        switch(lmId){
  		case 0:
  			classButtonDzh.setBackgroundResource(R.drawable.classtz_bottom_bar_button_dzh_select);
  			classButtonDzh.setOnClickListener(null);			
  			break;
  		case 1:
  			classButtonDxj.setBackgroundResource(R.drawable.classtz_bottom_bar_button_dxj_select);
  			classButtonDxj.setOnClickListener(null);
  			break;
  		case 2:
  			classButtonQch.setBackgroundResource(R.drawable.classtz_bottom_bar_button_qch_select);
  			classButtonQch.setOnClickListener(null);
  			break;
  		case 3:
  			classButtonYcq.setBackgroundResource(R.drawable.classtz_bottom_bar_button_ycq_select);
  			classButtonYcq.setOnClickListener(null);
  			break;
  		case 4:
  			classButtonRrss.setBackgroundResource(R.drawable.classtz_bottom_bar_button_rrss_select);
  			classButtonRrss.setOnClickListener(null);
  			break;
  		} 

        //loading动画
        loading = (LinearLayout) findViewById(R.id.top_bar_reload);
        loading.setOnClickListener(new View.OnClickListener() { 
            public void onClick(View v){
            	htmlHandler(url,page);
            } 
		});
        
        //帖子列表ListView
        classContent = (ListView) findViewById(R.id.classtz_content);
        classContent.setOnItemClickListener(this);
        //url="http://dzh.mop.com/plate/whbm/list.do?subName="+URLEncoder.encode("24小时回复榜");
        url=ClassArray.CLASSARRAY[lmId][classId][1]+"list.do";
        
        
        
        //当前页面信息
        pageInfo = (TextView) findViewById(R.id.top_pageinfo);
        pageInfo.setText("第"+page+"页");
        
     	//页面title
        topTitle = (TextView) findViewById(R.id.top_title);
        topTitle.setText(ClassArray.CLASSARRAY[lmId][classId][0]);
        
        //上一页
        topBarPrevious = (LinearLayout) findViewById(R.id.top_bar_previous);
        topBarPrevious.setOnClickListener(new View.OnClickListener() { 
            public void onClick(View v){
            	if(page <= 1){
            		showToast("当前已经是第一页了");
            	}else{
            		page -- ;
            		htmlHandler(url,page);
            		pageInfo.setText("第"+page+"页");
            	}
            } 
		});	
        
        //下一页
        topBarNext = (LinearLayout) findViewById(R.id.top_bar_next);
        topBarNext.setOnClickListener(new View.OnClickListener() { 
            public void onClick(View v){
            	page ++ ;
            	htmlHandler(url,page);
            	pageInfo.setText("第"+page+"页");
            } 
		});
        
        //more控制按钮
      	topBarMore = (LinearLayout) findViewById(R.id.top_bar_more);
      	topBarMore.setOnClickListener(new View.OnClickListener() {           
			public void onClick(View v){            	
            	if(!moreDisplay){
            		showMore();
      				moreDisplay = true;				
      			}else{
      				moreWindow.dismiss();
      				moreDisplay = false;
      			}
            } 
    	});
        
        //判断数据库是否有数据
        xmllists = new ArrayList<XMLFeed>();
        dbHelper = new DBHelper(this);		
		xmllists = dbHelper.getListData(0, 18);
		if (xmllists.isEmpty()== false && lmId == 0 && classId == 0){
			classContent.setAdapter(dbViewAdapter(xmllists));
		}else{
			//加载网络数据
	        htmlHandler(url,1);
			
		}
		
		//Menu菜单
		classtzMenu = (GridView) findViewById(R.id.classtz_menu_button);
		classtzMenu.setOnItemClickListener(this);
		classtz_menu_re = (RelativeLayout)findViewById(R.id.classtz_menu_re);
	        
		GridHandler handler = new GridHandler();
		handler.handlerMenu(lmId);
		gridlists = handler.getListFeed();
		List<Map<String, String>> lists = new ArrayList<Map<String, String>>();
		for (GridInfo info : gridlists){
			Map<String, String> map = new HashMap<String, String>();
			map.put("name", info.getName());
			map.put("url", info.getUrl());
			lists.add(map);
		}
		gridAdapter = new SimpleAdapter(this, lists, R.layout.classtz_menu_grid,
				new String[] {"name" }, new int[] {
							R.id.itemText});
			
		classtzMenu.setAdapter(gridAdapter);
	
    /////////////////////onCreate结束/////////////////////////    
    }
    
    //定义more
  	private PopupWindow moreWindow; 		
  	private LayoutInflater inflaterMore; 
  	private View layoutMore;
  	private LinearLayout classMore;
  	private FrameLayout classMoreBg;
  	//显示more
  	public void showMore(){	
  		inflaterMore = (LayoutInflater)this.getSystemService(LAYOUT_INFLATER_SERVICE);
  		layoutMore = inflaterMore.inflate(R.layout.classtz_more, null);
  		moreWindow = new PopupWindow(layoutMore,LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT); 
  		moreWindow.setAnimationStyle(R.style.MoreAnimation); 
  		moreWindow.showAtLocation(this.findViewById(R.id.classtz), Gravity.BOTTOM, 0, 0);
  		//more_bg
  		classMoreBg = (FrameLayout)layoutMore.findViewById(R.id.classtz_more_bg);
  		switch(moreNum){
  		case 1:
  			classMoreBg.setBackgroundResource(R.drawable.classtz_more_1);
  			break;
  		case 2:
  			classMoreBg.setBackgroundResource(R.drawable.classtz_more_2);
  			break;
  		case 3: 
  			classMoreBg.setBackgroundResource(R.drawable.classtz_more_3);
  			break;
  		case 4: 
  			classMoreBg.setBackgroundResource(R.drawable.classtz_more_4);
  			break;
  		case 5: 
  			classMoreBg.setBackgroundResource(R.drawable.classtz_more_5);
  			break;
  		}
  		//more_close
  		classMore = (LinearLayout)layoutMore.findViewById(R.id.classtz_more);						
  		classMore.setOnClickListener(new View.OnClickListener() { 
              public void onClick(View v){ 
              		moreWindow.dismiss();
              		moreDisplay = false;
                } 
  		});
  		//classMoreB1
  		classMoreB1 = (LinearLayout)layoutMore.findViewById(R.id.classtz_more_b1);						
  		classMoreB1.setOnClickListener(new View.OnClickListener() { 
            public void onClick(View v){
            	classMoreBg.setBackgroundResource(R.drawable.classtz_more_1);
            	moreWindow.dismiss();
            	url=ClassArray.CLASSARRAY[lmId][classId][1]+"list.do";
            	htmlHandler(url,1);
            	moreNum = 1;
            	page = 1;
            	pageInfo.setText("第"+page+"页");
              } 
		});
		//classMoreB2
  		classMoreB2 = (LinearLayout)layoutMore.findViewById(R.id.classtz_more_b2);						
  		classMoreB2.setOnClickListener(new View.OnClickListener() { 
            public void onClick(View v){
            	classMoreBg.setBackgroundResource(R.drawable.classtz_more_2);
            	moreWindow.dismiss();
            	url=ClassArray.CLASSARRAY[lmId][classId][1]+"list.do?subName="+URLEncoder.encode("24小时回复榜");
            	htmlHandler(url,1);
            	moreNum = 2;
            	page = 1;
            	pageInfo.setText("第"+page+"页");
              } 
		});
  		//classMoreB3
  		classMoreB3 = (LinearLayout)layoutMore.findViewById(R.id.classtz_more_b3);						
  		classMoreB3.setOnClickListener(new View.OnClickListener() { 
            public void onClick(View v){
            	classMoreBg.setBackgroundResource(R.drawable.classtz_more_3);
            	moreWindow.dismiss();
            	url=ClassArray.CLASSARRAY[lmId][classId][1]+"list.do?subName="+URLEncoder.encode("24小时点击榜");
            	htmlHandler(url,1);
            	moreNum = 3;
            	page = 1;
            	pageInfo.setText("第"+page+"页");
              } 
		});
  		//classMoreB4
  		classMoreB4 = (LinearLayout)layoutMore.findViewById(R.id.classtz_more_b4);						
  		classMoreB4.setOnClickListener(new View.OnClickListener() { 
            public void onClick(View v){
            	classMoreBg.setBackgroundResource(R.drawable.classtz_more_4);
            	moreWindow.dismiss();
            	url=ClassArray.CLASSARRAY[lmId][classId][1]+"list.do?subName="+URLEncoder.encode("热门贴");
            	htmlHandler(url,1);
            	moreNum = 4;
            	page = 1;
            	pageInfo.setText("第"+page+"页");
              } 
		});
  		//classMoreB5
  		classMoreB5 = (LinearLayout)layoutMore.findViewById(R.id.classtz_more_b5);						
  		classMoreB5.setOnClickListener(new View.OnClickListener() { 
            public void onClick(View v){
            	classMoreBg.setBackgroundResource(R.drawable.classtz_more_5);
            	moreWindow.dismiss();
            	url=ClassArray.CLASSARRAY[lmId][classId][1]+"list.do?subName="+URLEncoder.encode("精彩贴");
            	htmlHandler(url,1);
            	moreNum = 5;
            	page = 1;
            	pageInfo.setText("第"+page+"页");
              } 
		});
  	}
  	
  	//menu按钮动作
  	public boolean onKeyDown(int keyCode, KeyEvent event){
  		if(keyCode == KeyEvent.KEYCODE_MENU){
  			if(!menuDisplay){
  				classtz_menu_re.setAnimation(AnimationUtils.loadAnimation(this, R.anim.more_in));
  				classtz_menu_re.setVisibility(View.VISIBLE);  				
  				menuDisplay = true;				
  			}else{
  				classtz_menu_re.setAnimation(AnimationUtils.loadAnimation(this, R.anim.more_out));
  				classtz_menu_re.setVisibility(View.INVISIBLE);  				
  				menuDisplay = false;
  			}
  				
  			return false;
  		}else if(keyCode == KeyEvent.KEYCODE_BACK){
  			if(menuDisplay){
  				classtz_menu_re.setAnimation(AnimationUtils.loadAnimation(this, R.anim.more_out));
  				classtz_menu_re.setVisibility(View.INVISIBLE);
  				menuDisplay = false;
  			}else{
  				
  				showExitAlert();
  			}
  				
  			return false;
  		}else{
  			return false;
  		}
  			
  	}
  	   
    //发送url和页数
    public void htmlHandler(final String url, final int page){
    	
    	loading.setBackgroundResource(R.anim.loading);
        loadingAnim = (AnimationDrawable) loading.getBackground();
        loadingAnim.setOneShot(false);
    	loadingAnim.start();
    	final Handler handler = new Handler(){
    		@Override
			public void handleMessage(Message msg){
				if (msg.what == 1){
					loadingAnim.stop();
					loading.setBackgroundResource(R.drawable.top_bar_reload);	    	
					classContent.setAdapter(adapter);
				}
			}
		};
    	new Thread(){
    		public void run(){
    			Looper.prepare();
    			try{
					Thread.sleep(100);

				}catch (InterruptedException e){
					e.printStackTrace();
				}
    			try{
    				htmlConnect(url, page);
					setInListView();
    			}catch(Exception e){
    				
    			}
    			Message m = new Message();
				m.what = 1;
				handler.sendMessage(m);
				Looper.loop();
    		}
    	}.start();
    }
    
    //从网络取得数据填充ListView
    private void setInListView(){

    	List<Map<String, String>> lists = new ArrayList<Map<String, String>>();
    	
    	if (xmllists.isEmpty()){
    		showToast("数据请求异常，请重试或放弃！");
		}else{
			if (page == 1){
				dbHelper.deleteAllData();
			}
			for (XMLFeed feed : xmllists){
				Map<String, String> map = new HashMap<String, String>();
				map.put("class_content_title", feed.getTitle());
				map.put("class_content_hf", "回复："+feed.getHf());
				map.put("class_content_time", "时间："+feed.getTime());
				feed.getURL();

				lists.add(map);
				if (page == 1 && lmId == 0 && classId == 0){
					try {						
						dbHelper.save(feed);
						//Log.e("m20", feed.getURL());
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}
		adapter = new SimpleAdapter(this, lists, R.layout.classtz_content,
				new String[] { "class_content_title", "class_content_hf", "class_content_time" }, new int[] {
						R.id.classtz_content_title, R.id.classtz_content_hf, R.id.classtz_content_time});
		

	}
    
    //从数据库中取得数据填充ListView
    private SimpleAdapter dbViewAdapter(List<XMLFeed> xmllists){
    	
    	List<Map<String, String>> lists = new ArrayList<Map<String, String>>();
    	for (XMLFeed feed : xmllists){
			Map<String, String> map = new HashMap<String, String>();
			map.put("class_content_title", feed.getTitle());
			map.put("class_content_hf", "回复："+feed.getHf());
			map.put("class_content_time", "时间："+feed.getTime());

			lists.add(map);
		}
    	adapter = new SimpleAdapter(this, lists, R.layout.classtz_content,
				new String[] { "class_content_title", "class_content_hf", "class_content_time" }, new int[] {
						R.id.classtz_content_title, R.id.classtz_content_hf, R.id.classtz_content_time});
		return adapter;
		
    }
    
    //连接网络获取数据
    private void htmlConnect(String url, int page) throws Exception{

    	Map<String, String> map = new HashMap<String, String>();
		map.put("page", String.valueOf(page));

		HttpConnectionUtil conn = new HttpConnectionUtil();
		conn.syncConnect(url, map, HttpMethod.GET, new HttpConnectionCallback(){
			
			public void execute(String response){
				XMLHandler handler = new XMLHandler();

				handler.handlerClassA(response);
			
				xmllists = handler.getListFeed();
			}
		});

	}
    
    //ListView的按钮事件
  	public void onItemClick(AdapterView<?> arg0, View view, int position, long arg3){
  		
  		if (arg0 == classContent){
  			//Log.e("m20","L:"+arg0.toString());
	  		XMLFeed url = xmllists.get(position);
	  		Intent intent = new Intent();
	  		intent.putExtra("url", url);
	  		intent.setAction("com.m20studio.mop.activity.ViewTz");
	  		startActivity(intent);
  		}else if(arg0 == classtzMenu){
  			
  			GridInfo info = gridlists.get(position);
  			//Log.e("m20","G:"+info.getName());
  			if (info.getName().equals("关于")){
  				Intent intent = new Intent();
	        	intent.setAction("com.m20studio.mop.activity.About");
	        	startActivity(intent);
  			}else if (info.getName().equals("退出")){
  				showExitAlert();
  			}else if (info.getName().equals("帮助")){
  				Intent intent = new Intent();
	        	intent.setAction("com.m20studio.mop.activity.Help");
	        	startActivity(intent);
  			}else{
	  	  		Intent intent = new Intent();
	  	  		intent.putExtra("lmId", info.getLmId());
	  	  		intent.putExtra("classId", info.getClassId());
	  	  		intent.setAction("com.m20studio.mop.activity.ClassTZ");
	  	  		startActivity(intent);
  			}
  		}
  	}
  	
  	//退出提示框
  	private void showExitAlert() {
  		final AlertDialog dlg = new AlertDialog.Builder(this).create();
  		dlg.show();
  		Window window = dlg.getWindow();
  	    // *** 主要就是在这里实现这种效果的.
  	    // 设置窗口的内容页面,shrew_exit_dialog.xml文件中定义view内容
  		window.setContentView(R.layout.exit);
  	    // 为确认按钮添加事件,执行退出应用操作
  		ImageButton ok = (ImageButton) window.findViewById(R.id.btn_ok);
  		ok.setOnClickListener(new View.OnClickListener() {
  			public void onClick(View v) {
  				Intent startMain = new Intent(Intent.ACTION_MAIN);
  		        startMain.addCategory(Intent.CATEGORY_HOME);
  		        startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  		        startActivity(startMain);
  		        System.exit(0);
  			}
  		});
  		// 关闭alert对话框架
        ImageButton cancel = (ImageButton) window.findViewById(R.id.btn_cancel);
        cancel.setOnClickListener(new View.OnClickListener() {
        	public void onClick(View v) {
        		dlg.cancel();
        	}
	  });
  	}
  	
    
  	//信息提示框
    private void showToast(String str){
		Toast.makeText(this, str, 1).show();
	}
}